package mqlistener

import (
	log "ac-common-go/glog"
	"ac-julink/socket"
	"ac-julink/tool/data"
	hsjson "ac-julink/tool/json"
	"ac-julink/tool/procinfo"
	"ac-julink/tool/util"
	"errors"
	"strings"
	"time"
	//"github.com/jjeffery/stomp"
	"ac-julink/cache"
	"ac-julink/manager"
	"github.com/go-stomp/stomp"
)

func NewWgdataListener() *WgdataActiveMqListener {
	return &WgdataActiveMqListener{}
}

type WgdataActiveMqListener struct {
}

func (self *WgdataActiveMqListener) OnReceive(msg *stomp.Message, context *cache.SyncContext, client *manager.AcRestClient) (err error) {
	timeStart := time.Now().UnixNano()
	defer func() {
		if pErr := recover(); pErr != nil {
			log.Errorf("WgdataActiveMqListener OnReceive panic:%+v\n%s", pErr, util.PanicTrace())
		}
	}()
	if msg == nil || msg.Body == nil {
		return errors.New("stomp.Message invalid")
	}
	log.Infof("Wgdata MQ OnReceive:%s", string(msg.Body))
	_fdid, _wifiid, _json, _msgid, isHENC, err := DealWgdataCmdMq(string(msg.Body), context, client)
	if err != nil {
		if !strings.Contains(err.Error(), "on other sid") {
			log.Errorf("DealWgdataCmdMq failed !%+v", err)
		}
		return err
	}
	log.Infof("DealWgdataCmdMq wifiid[%s],fdid[%d]", _wifiid, _fdid)

	socketSession := socket.SocketManager.SessionMgr.GetSession(_fdid)
	if socketSession != nil {
		log.Infof("socketSession:[%s]", socketSession.WifiID())
		if strings.Compare(socketSession.WifiID(), _wifiid) != 0 {
			log.Errorf("Not Find Session!")
			return errors.New("Not Find Session!")
		}

		_result, err := PackageWgdataCmdMq(context, client, _wifiid, _json, isHENC)
		if err != nil {
			log.Errorf("DealWgdataCmdMq failed !%+v", err)
			return err
		}
		socketSession.SendMessage(_result)

	} else {
		log.Errorf("Get [%d] socketSession failed !", _fdid)
		return errors.New("socketSession is nil!")
	}
	log.Warningf("RECORD-WgdataMQ:%d,%s,%s,%dms,err:%+v", _msgid, _wifiid,
		socketSession.ClientIp(), (time.Now().UnixNano()-timeStart)/1e6, err)
	return nil
}

// 处理配置控制指令MQ消息
func DealWgdataCmdMq(_jsonstr string, context *cache.SyncContext, client *manager.AcRestClient) (fdid int, wifiid, reponse string, msgid int, _isHENC bool, err error) {
	var isHENC bool
	log.Infof("DealWgdataCmdMq:\n%s", _jsonstr)
	//1.解析MQ数据
	_wifiid, _devid, _dataType, _data, _id, _seq, _err, err := hsjson.MQParseMsgConfigControl(_jsonstr)
	if err != nil {
		log.Errorf("MQParseMsgCmdControl  failed! ", err)
		return 0, "", "", msgid, isHENC, err
	}
	//2.查询PS设备在线状态
	var online int
	var sid string
	//client := manager.GetClientFacade()
	resp, err := client.GetWifiStats(_wifiid)
	if err != nil {
		log.Errorf("GetWifiStats  failed! ", err)
		return 0, "", "", msgid, isHENC, err
	} else {
		if value, ok := resp["stat"]; ok && value != nil {
			online = int(value.(float64))
		}
		if value, ok := resp["owner"]; ok && value != nil {
			sid = value.(string)
		}
		if value, ok := resp["netid"]; ok && value != nil {
			fdid = int(value.(float64))
		}

		if value, ok := resp["cbcEnable"]; ok && value != nil {
			isHENC = value.(bool)
		}
	}
	if len(sid) == 0 {
		log.Errorf("sid in cannot be empty for [%v]!", resp)
		return fdid, _wifiid, "", msgid, isHENC, errors.New("invalid wifiStats, sid is nil!")
	}

	log.Infof("GetWifiStats online:%d,sid:%s,fdid:%d", online, sid, fdid)
	//3.判断设备是否在线,sid是否为此节点
	if online != 1 {
		log.Errorf("wifiid[%s] offline!", _wifiid)
		return fdid, _wifiid, "", msgid, isHENC, errors.New("Device is offline!")
	}

	if strings.Compare(data.Mysid, sid) != 0 {
		return fdid, _wifiid, "", msgid, isHENC, errors.New("Device on other sid!")
	}
	var _json string
	//4.根据消息ID
	if _id == data.SEND_CONFIG_DATA_COMMAND {
		msgid = 601
		procinfo.AddCount(msgid)
		//组装601下发JSON数据
		_json, err = hsjson.CmdConfigDataJsonCreate(_devid, _seq, _dataType, _data)
		if err != nil {
			log.Errorf("CmdControlJsonCreate failed !", err)
			return fdid, _wifiid, "", msgid, isHENC, err
		}
	} else if _id == data.REPORT_CONFIG_DATA {
		msgid = 602
		procinfo.AddCount(msgid)
		//组装601下发JSON数据
		_json, err = hsjson.ReportConfigDataJsonResult(_devid, _seq, _dataType, _data, _err)
		if err != nil {
			log.Errorf("CmdControlJsonCreate failed !", err)
			return fdid, _wifiid, "", msgid, isHENC, err
		}
	}

	return fdid, _wifiid, _json, msgid, isHENC, err
}

// xiaohong add
func PackageWgdataCmdMq(context *cache.SyncContext, client *manager.AcRestClient, _wifiid string, _json string, isHENC bool) (result string, err error) {
	pre_key, err := client.GetPublicKey(_wifiid, isHENC, context)
	log.Infof("pre_jey[%s]", pre_key)
	var _msgResult string
	//7.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult = data.PackageMsg(_json, pre_key)
	log.Infof("PackageWgdataCmdMq:[%s]", _msgResult)
	return _msgResult, err
}
